package com.gz.web.json;

import com.gz.web.json.entity.Dog;
import com.gz.web.json.entity.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;

//@Controller
//@ResponseBody  //如果写在这个，那下面的方法不用写，都默认返回json
//@Controller+@ResponseBody=@RestController
@RestController
public class JsonHandler {

    @RequestMapping(value = "/json/dog")
//    @ResponseBody //返回json格式数据
    public Dog save1() {
        Dog dog = new Dog("小白","汪汪");
        return dog;
    }

    @RequestMapping(value = "/json/user")
//    @ResponseBody //返回json格式数据
    public User save2(@RequestBody User user) {//@RequestBody将接收到的json格式数据转为对象
        System.out.println("user= "+user);
        return user;
    }

    //文件下载
    @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> downFile(HttpSession session) throws Exception {
        //构建一个ResponseEntity 对象
        //1.http响应头headers
        //2.http 响应状态
        //3.下载的文件

        //1.先获取到下载文件的inputstream
        InputStream resourceAsStream = session.getServletContext().getResourceAsStream("/img/3.png");

        //2.开辟一个存放文件的byte数组
        byte[] bytes = new byte[resourceAsStream.available()];

        //3.将下载的文件读入到byte[]
        resourceAsStream.read(bytes);

        // public ResponseEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers, HttpStatus status) {
        //        this(body, headers, (Object)status);
        //    }
        //4.创建返回的HttpStatus
        HttpStatus status = HttpStatus.OK;
        //5.创建headers
        HttpHeaders headers = new HttpHeaders();
        //Content-Disposition:指示如何处理相应内容
        //attachment:以附件形式下载
        headers.add("Content-Disposition", "attachment; filename=3.png");

        //根据3,4,5的内容填入到ResponseEntity
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status);

        return responseEntity;
    }
}
